package gu.simplemq.jms;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;  
/**
 * ACTIVEMQ 消息发送基类
 * @author guyadong
 *
 */
abstract class BaseSender  {

	public BaseSender() {
		super();
	}

	/**
	 * 创建消息发送对象
	 * @param session
	 * @param name name of queue or topic
	 * @return 消息消费对象
	 * @throws JMSException
	 */
	protected abstract MessageProducer makeSender(Session session,String name) throws JMSException;

	void doSend(Connection connection, String channel, Iterable<String> messages) throws JMSException {
		// 启动连接
		connection.start();
		// 创建会话
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		MessageProducer producer = null;
		// 创建一个生产者
		try {
	        producer = makeSender(session,channel);
	        for(String text : messages){
		        TextMessage message = session.createTextMessage(text);
		        // 发布消息
	            producer.send(message);
	        }
		} finally {
			if(null != producer){
				producer.close();
			}
			session.close();
		}
	}
	static class PublishSender extends BaseSender{
		public PublishSender() {
			super();
		}

		@Override
		protected MessageProducer makeSender(Session session, String name) throws JMSException {
			return session.createProducer(session.createTopic(name));
		}
	}
	static class ProducerSender extends BaseSender{
		public ProducerSender() {
			super();
		}
		@Override
		protected MessageProducer makeSender(Session session, String name) throws JMSException {
			return session.createProducer(session.createQueue(name));
		}
	}
}
